package com.hopoke.common.interceptors;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.hopoke.common.domain.Result;
import com.hopoke.common.expection.UnauthorizedException;
import com.hopoke.common.util.UserContext;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
@RequiredArgsConstructor
public class AuthInterceptors implements HandlerInterceptor {

    private final RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println(request.getRequestURL());
        String method = request.getMethod();
        if (StrUtil.equals(method, "OPTIONS")) {
            return true;
        }

        String token = request.getHeader("token");
        String str = redisTemplate.opsForValue().get("user:login" + token);
        if (StrUtil.isEmpty(str)) {
            writeAuthErrorToResponse(response);
            return false;
        }

        redisTemplate.expire("user:login" + token, 2, TimeUnit.DAYS);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.clear();
    }

    private void writeAuthErrorToResponse(javax.servlet.http.HttpServletResponse response) {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        try {
            writer = response.getWriter();
            Result<Object> errorBody = Result.error(new UnauthorizedException("用户未登录"));
            writer.print(JSON.toJSONString(errorBody));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(writer != null){
                writer.close();
            }
        }

    }
}
